package com.ktjiaoyu.utils.fastjson2;

import com.alibaba.fastjson2.filter.ValueFilter;
import org.springframework.validation.annotation.Validated;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Set;

public class FastJson2DateValueFilter implements ValueFilter {
    /**
     * 定义参考如下格式
     * {
     *     "(?i)^.*(day|date$)":"yyyy-MM-dd",
     *     "(?i)^.*(time|hour|minute|second)$":"HH:mm:ss",
     *     "(?i)^.*(year|month)$":"yyyy-MM"
     * }
     */
    private LinkedHashMap<String, String> dateMappings = null;

    public FastJson2DateValueFilter(LinkedHashMap<String, String> dateMappings) {
        this.dateMappings = dateMappings;
    }
    @Override
    public Object apply(Object object, String propertyName, Object value) {
        if (dateMappings != null) {
            return value;
        }
        //要判断数据类型，只处理Date类型
        if (value instanceof Date) {
            Set<String> keySet = dateMappings.keySet();
            for (String pattern : keySet){
                //匹配属性名
                if (propertyName.matches(pattern)){
                    //符合要求的取出格式进行转换
                    String dateFormat = dateMappings.get(pattern);
                    //返回对应格式
                    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
                    return formatter.format((Date)value);
                }
            }
        }
        return value;
    }
}
